import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

from constants import global_variable
from constants.global_variable import logger
from utils.http_utils import HttpUtils
from utils.proxy_utils import ProxyUtils


class AdsApi:
    # 创建浏览器
    @staticmethod
    def create_browser():
        url = global_variable.api_url + '/api/v2/browser-profile/create'
        hardware_config = ProxyUtils.generate_cpu_and_memory()
        json_data = {
            "group_id": "0",
            "fingerprint_config": {
                "automatic_timezone": "1", # 基于IP自动生成时区
                "location_switch": "1", # 基于IP自动生成位置
                "screen_resolution": "random", # 模拟安卓分辨率
                "language": ["zh-CN","zh"],
                "language_switch": "0", # 基于IP国家设置语言，0关闭
                "page_language_switch": "0", # 基于[语言]匹配界面语言，0关闭
                "page_language": "zh-CN", # 界面语言
                "ua": ProxyUtils.generate_android_ua(),
                "webrtc": "disabled", # disabled 禁用(默认)，网站会拿不到IP
                "hardware_concurrency": hardware_config["hardware_concurrency"], # CPU核数
                "device_memory": hardware_config["device_memory"], # RAM内存
                "device_name_switch": "1", #随机设备名称
                "canvas": 1, # 模拟真实浏览器的指纹抖动
                "webgl": 3, # 自动给你随机一个设备指纹
                "audio": 1  # 打乱浏览器的 AudioContext 输出，防止指纹识别。
            },
            "user_proxy_config": {
                "proxy_soft": "other",
                "proxy_host": global_variable.proxy_host,
                "proxy_port": global_variable.proxy_port,
                "proxy_type": global_variable.proxy_type,
                "proxy_user": ProxyUtils.generate_proxy_user(),
                "proxy_password": global_variable.proxy_password
            }
        }
        logger.info(f'创建浏览器请求参数: {str(json_data)}')
        r = HttpUtils.post(url, json=json_data).json()
        return r

    @staticmethod
    def start_browser(profile_id):
        open_url = global_variable.api_url + '/api/v2/browser-profile/start'
        json_data = {
            'profile_id': profile_id
        }
        resp = HttpUtils.post(open_url, json=json_data).json()
        logger.info(f'打开浏览器请求结果: {str(resp)}')
        if resp['code'] != 0:
            logger.error('打开浏览器异常')
            raise RuntimeError('打开浏览器异常')
        chrome_driver = resp['data']['webdriver']
        service = Service(executable_path=chrome_driver)
        chrome_options = Options()
        chrome_options.add_argument('--blink-settings=imagesEnabled=false')
        chrome_options.add_experimental_option('debuggerAddress', resp['data']['ws']['selenium'])
        web_driver = webdriver.Chrome(service=service, options=chrome_options)
        if not global_variable.is_debug:
            web_driver.set_window_size(300, 700)
        return web_driver

if __name__ == '__main__':
    profile_id = AdsApi.create_browser()['data']['profile_id']
    print(f'创建的环境id为{profile_id}')
    web_driver = AdsApi.start_browser(profile_id)
    time.sleep(5)
    web_driver.get('https://www.instagram.com/')
    time.sleep(5)
    print(web_driver.get_cookie('sessionid'))
    print('程序运行完成')
